<template>
  <div>
    <div style="padding: 0 20px">
      <el-row v-if="!readOnly && tipShow" type="flex" class="align-center" justify="space-between">
        <el-divider content-position="left">配置项</el-divider>
        <div v-if="data.length">
          <el-tooltip slot="header" effect="dark" content="只能有一个时间段配置"
                      placement="top"
          >
            <div>
              <el-button style="margin-left: 10px" type="primary" size="mini"
                         icon="el-icon-circle-plus-outline" :disabled="data.length>0" @click="addConfigClick"
              >增加配置
              </el-button>
            </div>
          </el-tooltip>
        </div>
        <el-button v-if="data.length ===0" type="primary" size="mini" icon="el-icon-circle-plus-outline"
                   style="margin-left: 10px" @click="addConfigClick"
        >增加配置
        </el-button>
      </el-row>
      <el-divider v-if="readOnly && !isWorkOrderShow && tipShow" content-position="left">
        {{ isHistory ? '历史配置项' : '配置项' }}
      </el-divider>
    </div>
    <el-button v-if="localErrorData!=null && localErrorData.error_type !== undefined" size="mini" type="danger"
               class="look_conflict_button"
               @click="errorDrawerShow = true"
    >查看冲突详情
    </el-button>
    <div style="padding: 0 20px">
      <el-card v-for="(item,index) in data" :key="index" shadow="never"
               style="margin-top: 15px"
      >
        <div slot="header">
          <div class="flex flex-no-wrap align-center justify-between">
            <div>
              <span class="text-bold" style="font-size: 16px">时间段</span>
              <el-date-picker v-model="item.date" type="daterange" size="mini" range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              value-format="yyyy-MM-dd"
                              format="yyyy年MM月dd日" style="margin-left: 20px"
                              :clearable="false" :readonly="readOnly"
                              @change="(val)=>{dateRangeChange(val,index)}"
              />
            </div>
            <div>
              <el-button v-if="showRelationWorkOrderBTN" type="primary" plain size="small"
                         @click="showOrder(index)"
              >关联工单
              </el-button>
              <el-tooltip slot="header" effect="dark" content="默认排斥该配置已选点位" placement="top">
                <el-button v-if="!readOnly" type="primary" plain size="small" icon="el-icon-circle-plus-outline"
                           @click="addPoint(index)"
                >
                  增加点位
                </el-button>
              </el-tooltip>
              <el-tooltip slot="header" effect="dark" content="默认排斥改配置已选楼盘" placement="top">
                <el-button v-if="!readOnly" type="primary" plain size="small"
                           icon="el-icon-circle-plus-outline" @click="addBuilding(index)"
                >增加楼盘
                </el-button>
              </el-tooltip>
              <!--              <el-tooltip slot="header" effect="dark" content="复用相同楼盘，重新选择时间段" placement="top">-->
              <!--                <el-button v-if="!readOnly" type="primary" plain size="small"-->
              <!--                           icon="el-icon-document-copy" @click="copyBuildingClick(index)"-->
              <!--                >复用楼盘-->
              <!--                </el-button>-->
              <!--              </el-tooltip>-->
              <el-button v-if="!readOnly" type="danger" plain size="small" icon="el-icon-delete"
                         @click="removeConfig(index)"
              >删除配置
              </el-button>
              <el-button v-if="isReplace && item.arr.find(id => id == 1)!==undefined" type="primary" plain size="small"
                         icon="el-icon-document"
                         @click="showBatchReplaceDialog(item.date,item.dataArr)"
              >批量换位
              </el-button>
            </div>
          </div>
          <div v-if="showRelationWorkOrderBTN" style="font-size: 12px;margin-top: 10px">
            已关联点位数
            <el-tooltip content="已经关联点位，点击可查看具体点位信息" placement="top">
              <span class="text-green" @click="showPointList(getRelationPointList(item))"
              >{{ getRelationPointList(item).length }}</span>
            </el-tooltip>
          </div>
        </div>
        <div>
          <el-divider content-position="center" class="text-bold" style="font-size: 12px!important;">选中的点位</el-divider>
          <el-table v-if="item.dataArr.length>0" :data="item.dataArr"
                    class="dataTable"
                    style="width: 100%"
                    max-height="700px"
                    header-row-class-name="text-bold table-herder" size="mini" :show-summary="true"
                    :summary-method="(params)=>{return choosePointSum(params,index)}"
                    row-class-name="choosed-data"
                    header-cell-class-name="choosed-data">
            <el-table-column prop="name" label="楼盘" min-width="100" align="center"/>
            <!--套餐信息-->
            <el-table-column v-if="item.type == 0" width="300" label="套餐" header-align="center">
              <template slot-scope="scope">
                <div v-for="(temp,xb) in scope.row.comboCountInfoList" :key="xb"
                     style="border: 1px solid #eee;margin: 15px 5px;padding: 10px 5px;position: relative">
                  <div style="font-size: 14px;font-weight: bold;position: absolute;top: -10px;background-color: white;width: 40px;left: 10px;">
                    {{ temp.name }}
                  </div>
                  <div v-for="(tmp,i) in temp.ruleList" :key="i" style="margin: 2px 0;font-size: 14px">
                    <span>{{ tmp.name }}：</span>
                    <span :class=" tmp.count>0?'text-red text-bold':''">{{ tmp.count }}</span>个
                  </div>
                </div>
                <div style="text-align: center">
                  <el-button v-if="!readOnly" type="primary" size="mini" @click="getBuildingData(scope.row,index)">
                    修改
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-for="point in item.arr" :key="point" align="center" :label="getPointTypeName(point)">
              <template slot-scope="scope">
                <div v-if="showNumBtn">
                  <el-button size="mini" type="text" class="text-underline text-bold"
                             @click="getPointData(point,scope.row.pointTypeCountVOMap,scope.row.id,index,item.type,item.date)">
                    {{ scope.row.pointTypeCountVOMap[point] ? scope.row.pointTypeCountVOMap[point].to : 0 }}
                  </el-button>
                  <span style="font-size: 12px">&nbsp;&nbsp;（{{(((scope.row.pointTypeCountVOMap[point] || {}).mediaPointList || [])[0] || {}).size_width + "*" + (((scope.row.pointTypeCountVOMap[point] || {}).mediaPointList || [])[0] || {}).size_height}}）</span>
                  <span v-if="point == 11" style="font-size: 12px">
                    {{
                      getSpecPriceName((((scope.row.pointTypeCountVOMap[point] || {}).mediaPointList || [])[0] || {}).media_type_spec_price_id)
                    }}
                  </span>
                </div>
                <div v-if="!showNumBtn">
                  <span type="text" class="text-bold">
                    {{ scope.row.pointTypeCountVOMap[point] ? scope.row.pointTypeCountVOMap[point].to : 0 }}
                  </span>
                  <span v-if="point == 11" style="font-size: 12px">
                    {{
                      getSpecPriceName((((scope.row.pointTypeCountVOMap[point] || {}).mediaPointList || [])[0] || {}).media_type_spec_price_id)
                    }}
                  </span>
                </div>
                <!--                <div v-if="item.type==0">-->
                <!--                  <el-button size="mini" type="text" class="text-underline text-bold"-->
                <!--                             @click="getPointData(point,scope.row.pointTypeCountVOMap,scope.row.id,index,item.type)"-->
                <!--                  >-->
                <!--                    {{ scope.row.pointTypeCountVOMap[point].to }}-->
                <!--                  </el-button>-->
                <!--                </div>-->
              </template>
            </el-table-column>
            <el-table-column v-if="isWorkOrderShow" align="center" label="安装工人" width="200" show-overflow-tooltip>
              <template slot-scope="scope">
                {{
                  scope.row.works.map(item => {
                    return item.name
                  }).join(',')
                }}
              </template>
            </el-table-column>
            <el-table-column v-if="!readOnly" label="操作" width="50px" align="center">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" icon="el-icon-delete" circle
                           @click="chooseTableRemove(index,scope.$index)"/>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <el-dialog :title="readOnly?'具体点位':'精准选点'" :visible.sync="programmeSelectPointDialogVisible" width="1200px" center
               append-to-body>
      <div v-if="!readOnly" style="font-size: 16px">
        共计<span class="text-green">{{ programmePointData.point_type_count }}</span>个空闲点位，
        最多可选<span class="text-red">{{ programmePointData.point_count }}</span>，
        已选择<span class="text-blue">{{ programmePointData.point_checked_count }}</span>个
        <span v-if="programmePointData.type==0">必须选择<span class="text-red">{{
            programmePointData.need_select_count
          }}</span>个</span>
        <el-checkbox v-model="programmePointData.isAllSelect" label="全选"
                     @change="(val)=>{allSelectCheckBoxChange(val,programmePointData.type,programmePointData.point_count)}"
        />
      </div>
      <el-row type="flex" style="flex-wrap: wrap">
        <div v-for="item in programmePointData.mediaPointData" :class="item.checked?'checked-box item':'item'"
             @click="programmeItemChange(item,programmePointData.type,programmePointData.point_count,programmePointData.point_checked_count )"
        >
          <div v-if="programmePointData.point_type_id!=9" style="display: table-cell;vertical-align: middle;">
            {{
              (item.building_number != null ? item.building_number + '号楼' : '') +
              (item.unit_number != null ? item.unit_number + '单元' : '') +
              (item.floor != null ? item.floor + '层' : '') + item.code
            }}
          </div>
          <div v-if="programmePointData.point_type_id==9" style="display: table-cell;vertical-align: middle;">
            {{ item.code + (item.ab_type_id == 57 ? 'A面' : 'B面') }}
          </div>
        </div>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="readOnly" size="mini" @click="programmeSelectPointDialogVisible = false">关  闭</el-button>
        <el-button v-if="!readOnly" size="mini" @click="programmeSelectPointDialogVisible = false">取 消</el-button>
        <el-button v-if="!readOnly" size="mini" type="primary"
                   @click="programmeConfirm(programmePointData.type,programmePointData.point_checked_count,programmePointData.need_select_count)"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="期望时间段" :visible.sync="centerDialogVisible" width="30%" center append-to-body
               @close="tmpIndex = -1"
    >
      <div style="text-align: center">
        <el-form label-width="100px">
          <el-form-item label="期望时间段">
            <el-date-picker
              v-model="date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-left: 5px"
              value-format="yyyy-MM-dd"
              format="yyyy年MM月dd日"
              :clearable="false"
              size="mini"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="copyBuilding">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="期望时间段" :visible.sync="addConfigDialogVisible" width="30%" center append-to-body
               @close="exclusion_config_arr=[]"
    >
      <div style="text-align: center">
        <el-form label-width="100px">
          <el-form-item label="期望时间段">
            <el-date-picker
              v-model="date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-left: 5px"
              value-format="yyyy-MM-dd"
              format="yyyy年MM月dd日"
              :clearable="false"
              size="mini"
            />
          </el-form-item>
          <!--          <el-form-item label="排斥的点位" style="margin-bottom: 0">-->
          <!--            <el-select v-model="exclusion_config_arr" multiple style="width: 350px" size="mini">-->
          <!--              <el-option v-for="item in configArr" :key="item.index" :value="item.index" :label="item.label"/>-->
          <!--            </el-select>-->
          <!--            <div class="text-red" style="text-align: left;padding-left: 40px;margin-top: -15px;">将排斥所选配置中的点位</div>-->
          <!--          </el-form-item>-->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addConfigDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addConfigConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-drawer :visible.sync="errorDrawerShow" direction="rtl" size="60%">
      <template v-if="localErrorData!=null && localErrorData.type == 2" slot="title">
        {{ localErrorData.dateBegin + '至' + localErrorData.dateEnd }}与
        {{ localErrorData.conflictSchemeNameList == null ? '未知' : localErrorData.conflictSchemeNameList.join(',') }}方案冲突
      </template>
      <template v-if="localErrorData!=null && localErrorData.type == 1" slot="title">
        {{ localErrorData.date1Begin + '至' + localErrorData.date1End }}时间段与
        {{ localErrorData.date2Begin + '至' + localErrorData.date2End }}时间段冲突
      </template>
      <div v-if="localErrorData != null">
        <el-table class="error-table" :data="localErrorData.repeatMediaPointList" border size="mini"
                  header-row-class-name="text-bold table-herder"
        >
          <el-table-column width="50" align="center" type="expand">
            <template slot-scope="scope">
              <div style="padding: 20px">
                <el-table :data="scope.row.pointTypeArrData" row-key="id" border size="mini"
                          :tree-props="{children:'points',hasChildren: 'hasChildren'}"
                >
                  <el-table-column label="点位类型" prop="name"/>
                  <el-table-column label="设备详情" prop="detail"/>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="楼盘" prop="name" width="200" align="center"/>
          <el-table-column label="总计" prop="count" min-width="100" align="center"/>
        </el-table>
      </div>
    </el-drawer>
    <combo-distribute-dialog :combo-data-list="combo_data_list" :building-name="comboDialogTmpBuildingName"
                             :show-dialog="comboDistributeDialogShow" :combo-point-type-arr="comboPointTypeArr"
                             @shut="closeComboDialog" @save="editBuildingCombo"
    />
    <!--精准选点组件-->
    <precise-point-selection :show="precisePointSelectionDialogVisible" :point-data="tmpPointDataList"
                             :media-type-id="clickMediaTypeId" :all-can-select-count="allCanSelectNum"
                             :need-select-count="need_select_count" :is-combo="isCombo == 0" :is-replace="isReplace"
                             :read-only="readOnly" :has-spec-id="hasSpecId"
                             :date-range="clickDateRange" @close="closePrecisePointSelectionDialog"
                             @save="saveSelectPoint" @replace="replacePoint" :is-init="isInit"
    />
    <!--批量换位-->
    <el-dialog title="批量换位" :visible.sync="bachReplaceDialogVisible" width="80%" center>
      <div>
        <el-form :inline="true" :model="replaceForm" ref="replaceForm" size="mini" label-width="80">
          <el-row style="font-size: 16px" :gutter="30">
            <el-col :span="11">
              <el-divider>需要更换的点位</el-divider>
              <div v-for="(item,index) in replaceForm.replacePointArr" :key="index"
                   style="text-align: center;position: relative;margin: 10px"
              >
                <i v-if="index===0" style="color: #00c300;font-size: 20px;position: absolute;left: 25px;top: 5px;"
                   class="el-icon-circle-plus-outline"
                   @click="add"
                />
                <el-form-item label="楼盘" :prop="'replacePointArr.'+index+'.building_area_id'"
                              :rules="{required: true, message: '楼盘不能为空', trigger: 'change'}"
                >
                  <el-select v-model="item.building_area_id" size="mini" @change="item.floor = null" filterable>
                    <el-option v-for="building in sourceBuildingArr" :key="building.id" :value="building.id"
                               :label="building.name"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="楼层" :prop="'replacePointArr.'+index+'.floor'"
                              :rules="{required: true, message: '楼层不能为空', trigger: 'change'}"
                >
                  <el-select v-model="item.floor" size="mini"
                             @change="item.point_list = getPointArr(item.building_area_id,item.floor,1)"
                  >
                    <el-option v-for="floor in getFloorArr(1,item.building_area_id)" :key="floor.floor"
                               :value="floor.floor" :label="floor.floor+'层'"
                               :disabled="getFloorDisable(item.building_area_id,floor.floor,1)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <span v-show="item.floor!=null">&nbsp;&nbsp;点位&nbsp;&nbsp;</span>
                  <el-button v-show="item.floor!=null" type="text" class="text-green" style="padding: 0"
                             @click="showBachReplacePointDialog(item.point_list)"
                  >&nbsp;{{ item.point_list.filter(item => item.checked == true).length }}&nbsp;
                  </el-button>
                  <i v-if="replaceForm.replacePointArr.length>1" class="el-icon-remove-outline"
                     style="font-size:20px;color:red;position: absolute;top: 5px"
                     @click="remove(index)"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="2">
              <div style="margin-top: 10px">
                <div class="flex">
                  <div
                    style="font-size:12px;width: 100px;height: 18px;margin-top: 6px;background-color: #409EFF;display: block;color: white;text-align: center;line-height: 18px"
                  >
                    替换成
                  </div>
                  <div class="to_right"/>
                </div>
              </div>
            </el-col>
            <el-col :span="11">
              <el-divider>替换的点位</el-divider>
              <div v-for="(item,index) in replaceForm.replacePointArr" :key="index"
                   style="text-align: center;position: relative;margin: 10px"
              >
                <el-form-item label="楼盘" :prop="'replacePointArr.'+index+'.to_building_area_id'" filterable
                              :rules="{required: true, message: '楼盘不能为空', trigger: 'change'}"
                >
                  <el-select v-model="item.to_building_area_id" size="mini" @change="item.to_floor = null">
                    <el-option v-for="building in targetBuildingArr" :key="building.id" :value="building.id"
                               :label="building.name"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="楼层" :prop="'replacePointArr.'+index+'.to_floor'"
                              :rules="{required: true, message: '楼层不能为空', trigger: 'change'}"
                >
                  <el-select v-model="item.to_floor" size="mini"
                             @change="item.to_point_list = getPointArr(item.to_building_area_id,item.to_floor,2)"
                  >
                    <el-option v-for="floor in getFloorArr(2,item.to_building_area_id)" :key="floor.floor"
                               :value="floor.floor" :label="floor.floor+'层'"
                               :disabled="getFloorDisable(item.to_building_area_id,floor.floor,2)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <span v-show="item.to_floor!=null">&nbsp;&nbsp;点位&nbsp;&nbsp;</span>
                  <el-button v-show="item.to_floor!=null" type="text" class="text-green" style="padding: 0"
                             @click="showBachReplacePointDialog(item.to_point_list)"
                  >
                    &nbsp;{{ item.to_point_list.filter(item => item.checked == true).length }}&nbsp;
                  </el-button>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="bachReplaceDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmReplacement">确 定</el-button>
      </span>
    </el-dialog>
    <precise-point-selection :show="precisePointSelectionDialogVisible2" :point-data="tmpReplacePointArr"
                             :media-type-id="tmpMediaTypeId" :all-can-select-count="tmpReplacePointArr.length"
                             @close="closePrecisePointSelectionDialog2"
                             @save="saveSelectPoint2" :is-init="isInit"
    />
  </div>
</template>

<script>
import { check_date_range_lock, combo_info, search } from '@/api/business/intention_scheme'
import { list_media_types } from '@/api/building/building'
import comboDistributeDialog from '@/components/PointPlanSetting/comboDistributeDialog'
import precisePointSelection from '@/components/PointPlanSetting/precisePointSelection'
import { batchReplacePoint } from '@/api/workOrder/workOrder'
import { all } from '@/api/system/media_type_spec_price'

export default {
  name: 'PointConfig', // 点位配置项组件
  components: { comboDistributeDialog, precisePointSelection },
  props: {
    data: { // 组件渲染的数据
      type: Array,
      default() {
        return []
      }
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    errorData: {
      type: Object,
      default() {
        return {}
      }
    },
    isWorkOrderShow: {
      type: Boolean,
      default: false
    },
    isReplace: {
      type: Boolean,
      default: false
    },
    workOrderId: {
      type: Number,
      default: 0
    },
    tipShow: {
      type: Boolean,
      default: true
    },
    isHistory: {
      type: Boolean,
      default: false
    },
    showRelationWorkOrderBTN: {
      type: Boolean,
      default: false
    },
    excludeSaleChooseId: {
      type: Number,
      default: null
    },
    hasSpecId: {
      type: Boolean,
      default: false
    },
    // 是否执行本身和子组件created生命周期中的初始化数据接口
    isInit: {
      type: Boolean,
      default: true
    },
    // 点位类型数据
    mediaTypeExtVOList: {
      type: Array,
      default() {
        return []
      }
    },
    // 价格类型数据
    mediaTypeSpecPriceVOList: {
      type: Array,
      default() {
        return []
      }
    },
    showNumBtn: {
      type: Boolean,
      default: true
    },
    hasDateRangeLimit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      date_range: [],
      errorDrawerShow: false,
      programmeSelectPointDialogVisible: false,
      centerDialogVisible: false,
      addConfigDialogVisible: false,
      point_type_arr: [],
      tmpIndex: -1,
      programmePointData: {
        id: null, // 楼盘ID
        type: null,
        need_select_count: null,
        index: 0,
        isAllSelect: false,
        point_type_id: null, // 点位类型
        point_count: null, // 可选总数
        point_type_count: null, // 总数
        point_checked_count: null, // 已选择数量
        mediaPointData: null, // 点位数据
        selectArr: []// 点位ID集合
      },
      exclusion_config_arr: [], // 排斥的配置项数据索引
      comboInfoList: [],
      combo_data_list: [],
      comboDialogTmpBuildingId: -1,
      comboDialogTmpBuildingName: '',
      comboDistributeDialogShow: false,
      localErrorData: [],
      precisePointSelectionDialogVisible: false,
      tmpPointDataList: [],
      tmpData: null,
      clickMediaTypeId: 0,
      allCanSelectNum: 0,
      need_select_count: 0,
      isCombo: null,
      clickDateRange: [],
      bachReplaceDialogVisible: false,
      replaceForm: {
        replacePointArr: [
          {
            building_area_id: null,
            floor: null,
            point_list: [],
            to_building_area_id: null,
            to_floor: null,
            to_point_list: []
          }
        ]
      },
      sourceBuildingArr: [], // 选择框数据来源
      targetBuildingArr: [], // 替换的数据来源
      tmpReplacePointArr: [],
      tmpMediaTypeId: null,
      precisePointSelectionDialogVisible2: false,
      media_type_spec_price_arr: []
    }
  },
  computed: {
    // 配置的点位
    configArr() {
      const tmp = []
      for (let i = 0; i < this.data.length; i++) {
        tmp.push({
          index: i,
          label: this.data[i].date[0] + '~' + this.data[i].date[1]
        })
      }
      return tmp
    },
    comboPointTypeArr() {
      return this.point_type_arr.filter(item => item.gas)
    }
  },
  watch: {
    errorData: {
      handler(val) {
        this.localErrorData = val
      },
      deep: true
    },
    mediaTypeExtVOList: {
      handler(val) {
        // 当组件不需要请求接口拿到初始化数据时 使用传入的数据
        if (!this.isInit) {
          this.point_type_arr = val
        }
      },
      deep: true,
      immediate: true
    },
    mediaTypeSpecPriceVOList: {
      handler(val) {
        // 当组件不需要请求接口拿到初始化数据时 使用传入的数据
        if (!this.isInit) {
          this.media_type_spec_price_arr = val
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.date_range = [this.getDateStr(new Date()), this.getDateStr(new Date())]
    if (this.isInit) {
      this.initPointType()
      this.initMediaTypeSpecPriceArr()
    }
    // this.initComboDetail()
  },
  methods: {
    addConfigClick() {
      this.addConfigDialogVisible = true
    },
    dateRangeChange(val, index) {
      const data = this.formatRequest(this.data[index])
      const req = {
        exclude_sale_choose_id: this.excludeSaleChooseId,
        dataList: []
      }
      req.dataList.push(data)
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      check_date_range_lock(req).then(
        res => {
          this.localErrorData = res.data
          if (this.localErrorData != null) {
            this.formatErrorData(index, this.data[index].type)
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    addPoint(index) {
      const data = this.formatRequest(this.data[index])
      const pointArr = data.pointList.map(t => {
        return t.id
      })
      this.$emit('setSearchConfig', index, 1, this.data[index].date, pointArr, this.data[index].arr.map(id => {
        return parseInt(id)
      }), this.data[index].type, true)
    },
    addBuilding(index) {
      const buildingIdArr = this.data[index].dataArr.map(item => {
        return item.id
      })
      this.$emit('setSearchConfig', index, 2, this.data[index].date, buildingIdArr, this.data[index].arr.map(id => {
        return parseInt(id)
      }), this.data[index].type, true)
    },
    copyBuildingClick(index) {
      this.tmpIndex = index
      this.centerDialogVisible = true
    },
    removeConfig(index) {
      this.$confirm('确定删除此配置项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('removeConfig', index)
      }).catch(() => {
      })
    },
    // 配置项点位数量求和
    choosePointSum(param, i) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (this.data[i].type == 0) {
          let s1 = 0
          if (index == 1) {
            const map = new Map()
            for (let j = 0; j < data.length; j++) {
              data[j].comboCountInfoList.forEach(item => {
                if (map.has(item.name)) {
                  map.set(item.name, item.count + map.get(item.name))
                } else {
                  map.set(item.name, item.count)
                }
              })
            }
            s1 = ''
            map.forEach(function(value, key) {
              s1 += key + '：' + value + '  '
            })
          } else if (this.readOnly) {
            for (let j = 0; j < data.length; j++) {
              if (this.comboPointTypeArr.length > 0) {
                s1 += data[j].pointTypeCountVOMap[this.comboPointTypeArr[index - 2].id].to
              }
            }
          } else {
            if (index != columns.length - 1) {
              for (let j = 0; j < data.length; j++) {
                if (this.comboPointTypeArr.length > 0) {
                  s1 += data[j].pointTypeCountVOMap[this.comboPointTypeArr[index - 2].id].to
                }
              }
            } else {
              s1 = ''
            }
          }
          sums[index] = s1
        } else {
          if (!this.readOnly) {
            if (index != columns.length - 1) {
              sums[index] = 0
              for (let j = 0; j < data.length; j++) {
                sums[index] += data[j].pointTypeCountVOMap[this.data[i].arr[index - 1]] ? data[j].pointTypeCountVOMap[this.data[i].arr[index - 1]].to : 0
              }
            }
          } else {
            sums[index] = 0
            for (let j = 0; j < data.length; j++) {
              sums[index] += data[j].pointTypeCountVOMap[this.data[i].arr[index - 1]] ? data[j].pointTypeCountVOMap[this.data[i].arr[index - 1]].to : 0
            }
          }
        }
      })
      if (this.isWorkOrderShow) {
        sums[sums.length - 1] = ''
      }
      return sums
    },
    getPointTypeName(id) {
      const tmp = this.point_type_arr.find(item => item.id == id)
      if (tmp) {
        return tmp.name
      } else {
        return ''
      }
    },
    getPointData(pointTypeId, data, buildingId, index, type, date) {
      if (this.readOnly) {
        if (data[pointTypeId].to > 0) {
          this.showAllPoint(pointTypeId, data[pointTypeId], buildingId, index, type, date)
        } else {
          this.$message.warning('没有选择点位')
        }
      } else {
        const req = {
          beginDate: this.data[index].date[0],
          endDate: this.data[index].date[1],
          buildingList: [{ id: buildingId }],
          pointTypeIdList: [pointTypeId],
          buildingRadiation: false,
          must_include_media_id_list: data[pointTypeId] ? data[pointTypeId].mediaPointList.filter(item => item.checked == true).map(item => {
            return item.id
          }) : [],
          exclude_sale_choose_id: this.excludeSaleChooseId
        }
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        // 请求接口获取数据
        search(req).then(
          res => {
            if (res.data.length > 0) {
              if (data[pointTypeId] != undefined && data[pointTypeId].to != 0) {
                this.$set(res.data[0].pointTypeCountVOMap[pointTypeId], 'to', data[pointTypeId].to)
              } else {
                this.$set(res.data[0].pointTypeCountVOMap[pointTypeId], 'to', 0)
              }
              if (data[pointTypeId] != undefined) {
                data[pointTypeId].mediaPointList.forEach(item => {
                  if (item.checked) {
                    const point = res.data[0].pointTypeCountVOMap[pointTypeId].mediaPointList.find(i => i.id == item.id)
                    if (point) {
                      point.checked = true
                      point.media_type_spec_price_id = item.media_type_spec_price_id
                      if (item.work_order_id !== null) {
                        point.work_order_id = item.work_order_id
                        point.relation_point = item.relation_point
                      }
                    }
                  }
                })
              }
              this.$set(data, pointTypeId, res.data[0].pointTypeCountVOMap[pointTypeId])
            } else {
              const tmp = {
                mediaPointList: [],
                point_type_count: 0,
                point_type_id: pointTypeId,
                to: 0
              }
              this.$set(data, pointTypeId, tmp)
            }
            this.showAllPoint(pointTypeId, data[pointTypeId], buildingId, index, type, date)
            loading.close()
          }
        ).catch(() => {
          loading.close()
        })
      }
    },
    chooseTableRemove(i, index) {
      this.$confirm('确定删除此楼盘?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('removeConfigBuilding', i, index)
      }).catch(() => {
      })
    },
    allSelectCheckBoxChange(val, type, max) {
      if (val) {
        if (type) {
          this.programmePointData.selectArr = []
          this.programmePointData.mediaPointData.forEach(item => {
            item.checked = true
            this.programmePointData.selectArr.push(item.id)
          })
        } else {
          const count = this.programmePointData.mediaPointData.filter(item => item.checked == true).length
          if (max > count) {
            this.programmePointData.mediaPointData.forEach(item => {
              if (!item.checked && max - count > 0) {
                item.checked = true
                max--
                this.programmePointData.selectArr.push(item.id)
              }
            })
          }
          // this.programmePointData.selectArr = []
          // this.programmePointData.mediaPointData.forEach(item => {
          //   item.checked = true
          //   this.programmePointData.selectArr.push(item.id)
          // })
        }
        this.programmePointData.point_checked_count = max
      } else {
        this.programmePointData.mediaPointData.forEach(item => {
          item.checked = false
        })
        this.programmePointData.selectArr = []
        this.programmePointData.point_checked_count = 0
      }
    },
    programmeItemChange(item, type, max, num) {
      if (!this.readOnly) {
        if (type == 0 && max == num && !(item.checked)) {
          this.$message.error('套餐类型不可增加点位')
          return
        }
        if (item.checked) {
          this.programmePointData.point_checked_count -= 1
          this.programmePointData.selectArr = this.programmePointData.selectArr.filter(t => t != item.id)
        } else {
          this.programmePointData.point_checked_count += 1
          this.programmePointData.selectArr.push(item.id)
        }
        item.checked = !item.checked
      }
    },
    programmeConfirm(type, selectNum, needSelectNum) {
      if (type == 0 && selectNum < needSelectNum) {
        this.$message.error('必须选择' + needSelectNum + '个点位')
        return
      }
      this.$emit('editConfig', this.programmePointData.index, this.programmePointData.id, this.programmePointData.point_type_id, this.programmePointData.mediaPointData)
      this.programmeSelectPointDialogVisible = false
    },
    addConfigConfirm() {
      if (this.hasDateRangeLimit && this.date_range[0] !== this.date_range[1]) {
        this.$message.error('换画类型锁位开始时间和结束时间应该为同一天')
        return
      }
      let arr = []
      this.exclusion_config_arr.forEach(item => {
        const data = this.formatRequest(this.data[item])
        arr = arr.concat(data.pointList.map(t => {
          return t.id
        }))
      })
      this.$emit('setSearchConfig', -1, 1, this.date_range, arr, [], 1, false)
      this.addConfigDialogVisible = false
    },
    copyBuilding() {
      const buildingIdArr = this.data[this.tmpIndex].dataArr.map(item => {
        return item.id
      })
      this.$emit('setSearchConfig', -1, 3, this.date_range, buildingIdArr, [], this.data[this.tmpIndex].type, false)
      this.centerDialogVisible = false
    },
    formatErrorData(index, type) {
      this.localErrorData.repeatMediaPointList.forEach(item => {
        let count = 0
        const arr = []// 第二个遍历每层的数据
        Object.keys(item.media_point_list_map).forEach(i => {
            count += item.media_point_list_map[i].length
            // 整理数组数据
            arr.push({
              id: 'type' + i,
              name: this.getPointTypeName(i) + '(' + item.media_point_list_map[i].length + ')',
              points: item.media_point_list_map[i]
            })
            // 加入点位详情
            this.data[index].dataArr.forEach(tmp => {
              if (item.id == tmp.id) {
                item.media_point_list_map[i].forEach(point => {
                  // 加入detail属性
                  let str = ''
                  if (i == 9) { // 综合市场类型
                    str = point.ab_type_id == 57 ? 'A面' : 'B面'
                  } else {
                    str = (point.building_number != null ? point.building_number + '号楼' : '') +
                      (point.unit_number != null ? point.unit_number + '单元' : '') +
                      (point.floor != null ? point.floor + '层' : '') + point.code
                  }
                  this.$set(point, 'detail', str)
                  // 去掉可选中的数据
                  if (this.localErrorData.type == 2 && type == 1) {
                    tmp.pointTypeCountVOMap[i].to--
                    tmp.pointTypeCountVOMap[i].mediaPointList.forEach(p => {
                      if (p.id == point.id) {
                        p.checked = false
                      }
                    })
                  }
                })
              }
            })
          }
        )
        // 加上楼盘统计
        this.$set(item, 'count', count)
        // 加入点位数据
        this.$set(item, 'pointTypeArrData', arr)
      })
      this.$message.warning('点位有冲突,可点击按钮查看冲突详情')
    },
    getDateStr(date) {
      return date.getFullYear() + '-' + ((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)) + '-' + (date.getDate() > 9 ? date.getDate() : ('0' + date.getDate()))
    },
    /**
     * 初始化点位类型数据
     */
    initPointType() {
      list_media_types().then(
        res => {
          this.point_type_arr = res.data
        }
      )
    },
    /**
     * 获取套餐详情
     */
    initComboDetail() {
      combo_info().then(res => {
        this.comboInfoList = res.data
        this.comboInfoList.forEach(item => {
          for (let i = 0; i < item.ruleList.length; i++) {
            item.ruleList[i].level = i + 1
          }
          item.ruleList.sort(function(a, b) {
            return a.level - b.level
          })
        })
      })
    },
    // 显示所有点位
    showAllPoint(typeId, data, id, index, type, date) {
      if (data.point_type_count == 0) {
        this.$message({
          message: '无可选点位',
          type: 'warning'
        })
      } else {
        this.tmpPointDataList = data.mediaPointList
        this.clickMediaTypeId = parseInt(typeId)
        this.isCombo = type
        if (this.isCombo == 0) {
          this.allCanSelectNum = data.to
        } else {
          this.allCanSelectNum = data.point_type_count
        }
        this.tmpData = data
        this.need_select_count = data.to
        this.precisePointSelectionDialogVisible = true
        this.clickDateRange = date
        this.programmePointData.id = id
        // this.programmePointData.type = type
        this.programmePointData.index = index
        // this.programmePointData.selectArr = []
        // this.programmePointData.isAllSelect = false
        // this.programmePointData.point_type_id = typeId
        // if (type == 1) {
        //   this.programmePointData.point_count = data.point_type_count
        // } else {
        //   this.programmePointData.point_count = data.to
        // }
        // this.programmePointData.point_type_count = data.point_type_count
        // this.programmePointData.point_checked_count = data.to
        // this.programmePointData.need_select_count = data.to
        // this.programmePointData.mediaPointData = []
        // data.mediaPointList.forEach(item => {
        //   if (item.checked) {
        //     this.programmePointData.selectArr.push(item.id)
        //   }
        //   this.programmePointData.mediaPointData.push(Object.assign({}, item))
        // })
        // this.programmeSelectPointDialogVisible = true
      }
    },
    /**
     * 格式化请求对象
     * @param data
     */
    formatRequest(data) {
      const newData = {}
      newData.beginDate = data.date[0]
      newData.endDate = data.date[1]
      newData.pointList = []
      newData.comboInfoList = []
      for (let i = 0; i < data.dataArr.length; i++) {
        data.arr.forEach(item => {
          if (data.dataArr[i].pointTypeCountVOMap[item]) {
            data.dataArr[i].pointTypeCountVOMap[item].mediaPointList.forEach(
              i => {
                if (i.checked) {
                  newData.pointList.push(i)
                }
              }
            )
          }
        })
        if (data.dataArr[i].comboCountInfoList && data.dataArr[i].comboCountInfoList.length > 0) {
          data.dataArr[i].comboCountInfoList.forEach(combo => {
            combo.ruleList.forEach(rule => {
              newData.comboInfoList.push(Object.assign({}, rule))
            })
          })
        }
      }
      return newData
    },
    /**
     * 获取楼盘数据
     * @param row
     * @param index
     */
    getBuildingData(row, index) {
      const req = {
        beginDate: this.data[index].date[0],
        endDate: this.data[index].date[1],
        buildingList: [{ id: row.id }],
        pointTypeIdList: this.data[index].arr,
        buildingRadiation: false,
        must_include_media_id_list: []
      }
      this.data[index].arr.forEach(pointTypeId => {
        req.must_include_media_id_list = req.must_include_media_id_list.concat(row.pointTypeCountVOMap[pointTypeId].mediaPointList.filter(item => item.checked == true).map(item => {
          return item.id
        }))
      })
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      search(req).then(
        res => {
          const keys = Object.keys(row.pointTypeCountVOMap)
          for (let i = 0; i < keys.length; i++) {
            const key = keys[i]
            res.data[0].pointTypeCountVOMap[key].mediaPointList.forEach(point => {
              const t = row.pointTypeCountVOMap[key].mediaPointList.find(item => item.id == point.id)
              if (t == undefined) {
                this.$set(point, 'checked', false)
                row.pointTypeCountVOMap[key].mediaPointList.push(point)
                row.pointTypeCountVOMap[key].point_type_count++
              }
            })
            row.pointTypeCountVOMap[key].mediaPointList.forEach(point => {
              const t = res.data[0].pointTypeCountVOMap[key].mediaPointList.find(item => item.id == point.id)
              if (t == undefined) {
                row.pointTypeCountVOMap[key].mediaPointList = row.pointTypeCountVOMap[key].mediaPointList.filter(i => i.id != point.id)
                row.pointTypeCountVOMap[key].point_type_count--
              }
            })
          }
          this.showBuildingCombo(row, index)
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    /**
     * 修改楼盘的套餐数据
     * [
     *   {
     *     combo_id:套餐ID
     *     rule_id:组合ID
     *     name:XX套餐-XX组合
     *     pointDataMap:{
     *       5:{ // 点位类型为key
     *         need_num:2, 组合所需要的数量
     *         total_num:2 点位可用数的总量
     *       }
     *     }
     *     distribution_num:分配数
     *   }
     * ]
     */
    showBuildingCombo(row, index) {
      const that = this
      this.tmpIndex = index
      const tmpArr = []
      this.comboInfoList.forEach(function(value, index) {
          value.ruleList.forEach(function(item, i) {
            const comboData = {}
            comboData.combo_id = value.combo_id
            comboData.rule_id = item.rule_id
            comboData.name = String.fromCharCode(index + 65) + '套餐' + '——' + String.fromCharCode(i + 65) + '组合'
            comboData.pointDataMap = {}
            that.comboPointTypeArr.forEach(point => {
              comboData.pointDataMap[point.id] = {
                need_num: 0,
                total_num: 0
              }
            })
            // 加入必须分配数
            item.mediaType2CountList.forEach(point => {
              comboData.pointDataMap[point.media_type_id].need_num = point.count
            })
            tmpArr.push(comboData)
          })
        }
      )
      // 处理套餐分配数
      row.comboCountInfoList.forEach(item => {
        item.ruleList.forEach(i => {
          tmpArr.forEach(combo => {
            if (combo.combo_id == i.combo_id && combo.rule_id == i.rule_id) {
              combo.distribution_num = i.count
            }
          })
        })
      })
      // 点位总数
      for (const key in row.pointTypeCountVOMap) {
        tmpArr.forEach(combo => {
          combo.pointDataMap[key].total_num = row.pointTypeCountVOMap[key].point_type_count
        })
      }
      this.combo_data_list = tmpArr.map(item => {
        return Object.assign({}, item)
      })
      this.comboDialogTmpBuildingId = row.id
      this.comboDialogTmpBuildingName = row.name
      this.comboDistributeDialogShow = true
    },
    closeComboDialog() {
      this.comboDistributeDialogShow = false
      this.comboDialogTmpBuildingId = null
      this.tmpIndex = -1
    },
    editBuildingCombo(comboDataList, use_count_map) {
      const buildingData = this.data[this.tmpIndex].dataArr.find(item => item.id == this.comboDialogTmpBuildingId)
      comboDataList.forEach(combo => {
        // 改变组合的数字
        buildingData.comboCountInfoList.forEach(item => {
          item.ruleList.forEach(rule => {
            if (combo.combo_id == rule.combo_id && combo.rule_id == rule.rule_id) {
              rule.count = combo.distribution_num
            }
          })
        })
      })
      buildingData.comboCountInfoList.forEach(item => {
        let count = 0
        item.ruleList.forEach(rule => {
          count += rule.count
        })
        item.count = count
      })
      // 根据数量改变点位状态
      const keys = use_count_map.keys()
      for (const key of keys) {
        const point = buildingData.pointTypeCountVOMap[key]
        if (point) {
          let num = use_count_map.get(key) - point.to
          point.to = use_count_map.get(key)
          if (num > 0) {
            point.mediaPointList.forEach(item => {
              if (num > 0 && !item.checked) {
                item.checked = true
                num--
              }
            })
          } else {
            for (let i = point.mediaPointList.length - 1; i >= 0; i--) {
              if (num < 0 && point.mediaPointList[i].checked) {
                point.mediaPointList[i].checked = false
                num++
              }
            }
          }
        }
      }
      this.closeComboDialog()
    },
    closePrecisePointSelectionDialog() {
      this.precisePointSelectionDialogVisible = false
      this.tmpPointDataList = []
      this.clickDateRange = []
      this.programmePointData.id = null
      this.programmePointData.index = null
    },
    /**
     * 保存选中的点位
     */
    saveSelectPoint(ids, points) {
      this.tmpData.to = ids.length
      this.tmpPointDataList.forEach(point => {
        if (ids.find(id => id == point.id) === undefined) {
          point.checked = false
          point.work_order_id = null
          if (point.relation_point !== undefined) {
            point.relation_point.is_relation = false
            point.relation_point.relation_point = null
          }
        } else {
          let find = points.find(item => item.id === point.id)
          if (find) {
            point.media_type_spec_price_id = find.media_type_spec_price_id
          }
          point.checked = true
        }
      })
    },
    replacePoint(source, target, vc) {
      this.$emit('replace', source, target, this.programmePointData.id, this.programmePointData.index, this.clickMediaTypeId, vc)
    },
    showBachReplacePointDialog(arr) {
      this.tmpReplacePointArr = arr
      this.tmpMediaTypeId = arr[0].media_type_id
      this.precisePointSelectionDialogVisible2 = true
    },
    add() {
      this.replaceForm.replacePointArr.push({
        building_area_id: null,
        floor: null,
        point_list: [],
        to_building_area_id: null,
        to_floor: null,
        to_point_list: []
      })
    },
    remove(index) {
      this.replaceForm.replacePointArr.splice(index, 1)
    },
    closePrecisePointSelectionDialog2() {
      this.precisePointSelectionDialogVisible2 = false
      this.tmpReplacePointArr = []
      this.tmpMediaTypeId = null
    },
    saveSelectPoint2(ids, points) {
      this.tmpReplacePointArr.forEach(point => {
        if (ids.find(id => id == point.id) === undefined) {
          point.checked = false
        } else {
          let find = points.find(item => item.id === point.id)
          if (find) {
            point.media_type_spec_price_id = find.media_type_spec_price_id
          }
          point.checked = true
        }
      })
    },
    /**
     *
     * @param date
     * @param sourceData
     */
    showBatchReplaceDialog(date, sourceData) {
      this.replaceForm.replacePointArr = [
        {
          building_area_id: null,
          floor: null,
          point_list: [],
          to_building_area_id: null,
          to_floor: null,
          to_point_list: []
        }
      ]
      const req = {
        beginDate: date[0],
        endDate: date[1],
        pointTypeIdList: [1],
        buildingRadiation: false
      }
      this.sourceBuildingArr = this.formatData(sourceData)
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        body: true,
        background: 'rgba(0, 0, 0, 0.7)'
      })
      search(req).then(res => {
        this.targetBuildingArr = this.formatData(res.data)
        this.bachReplaceDialogVisible = true
        this.$refs.replaceForm.clearValidate()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    /**
     * 格式化原楼盘数据 按楼层分类
     * @param data
     * @returns {*[]}
     */
    formatData(data) {
      const arr = []
      data.forEach(building => {
        let buildingData = {}
        buildingData.id = building.id
        buildingData.name = building.name
        buildingData.floorArr = []
        building.pointTypeCountVOMap[1].mediaPointList.forEach(point => {
          if (point.checked === undefined) {
            this.$set(point, 'checked', true)
          }
          let floor = buildingData.floorArr.find(floor => floor.floor == point.floor)
          if (floor !== undefined) {
            floor.floor = point.floor
            floor.pointList.push(Object.assign({}, point))
          } else {
            floor = {}
            floor.floor = point.floor
            floor.pointList = []
            floor.pointList.push(Object.assign({}, point))
            buildingData.floorArr.push(floor)
          }
        })
        arr.push(buildingData)
      })
      return arr
    },
    getFloorArr(type, buildingId) {
      if (!buildingId) {
        return []
      }
      let find
      if (type == 1) {
        find = this.sourceBuildingArr.find(building => building.id == buildingId)
      } else {
        find = this.targetBuildingArr.find(building => building.id == buildingId)
      }
      if (find) {
        return find.floorArr
      } else {
        return []
      }
    },
    getPointArr(buildingId, floor, type) {
      if (!buildingId || !floor) {
        return []
      }
      let building
      if (type == 1) {
        building = this.sourceBuildingArr.find(building => building.id == buildingId)
      } else {
        building = this.targetBuildingArr.find(building => building.id == buildingId)
      }
      if (building) {
        let t = building.floorArr.find(item => item.floor == floor)
        if (t.pointList) {
          return t.pointList
        } else {
          return []
        }
      } else {
        return []
      }
    },
    /**
     * 获取楼盘是否禁用
     */
    getFloorDisable(buildingId, floor, type) {
      let flag = false
      this.replaceForm.replacePointArr.forEach(item => {
        if (type == 1) {
          if (item.building_area_id == buildingId && item.floor == floor) {
            flag = true
          }
        } else {
          if (item.to_building_area_id == buildingId && item.to_floor == floor) {
            flag = true
          }
        }
      })
      return flag
    },
    confirmReplacement() {
      this.$refs.replaceForm.validate(validate => {
        if (validate) {
          let obj = this.checkBatchReplaceData()
          if (obj.source_count !== obj.target_count) {
            this.$message.error('需要更换的点位和替换的点位总和不相等，请调整')
            return
          }
          if (obj.source_count === 0) {
            this.$message.error('需要更换的点位总和不能为零请调整')
            return
          }
          const data = {
            work_order_id: this.workOrderId,
            old_device_ids: [],
            new_device_ids: []
          }
          this.replaceForm.replacePointArr.forEach(item => {
            data.old_device_ids = data.old_device_ids.concat(item.point_list.filter(point => point.checked === true).map(point => {
              return point.id
            }))
            data.new_device_ids = data.new_device_ids.concat(item.to_point_list.filter(point => point.checked === true).map(point => {
              return point.id
            }))
          })
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            body: true,
            background: 'rgba(0, 0, 0, 0.7)'
          })
          batchReplacePoint(data).then(res => {
            if (res.data) {
              this.$message.success('操作成功')
              this.bachReplaceDialogVisible = false
              this.$emit('reload')
            }
            loading.close()
          }).catch(() => {
            this.$message.error('操作失败')
            loading.close()
          })
        }
      })
    },
    /**
     * 检查替换的数据
     */
    checkBatchReplaceData() {
      let source_count = 0
      let target_count = 0
      this.replaceForm.replacePointArr.forEach(item => {
        source_count += item.point_list.filter(point => point.checked === true).length
        target_count += item.to_point_list.filter(point => point.checked === true).length
      })
      return { source_count, target_count }
    },
    showPointList(arr) {
      this.$emit('showPointList', arr)
    },
    /**
     * 显示关联工单
     * @param index
     */
    showOrder(index) {
      this.$emit('showOrder', index)
    },
    /**
     * 获取每个配置的关联点位
     * @param item
     * @returns {*[]}
     */
    getRelationPointList(item) {
      let arr = []
      item.dataArr.forEach(building => {
        for (let key in building.pointTypeCountVOMap) {
          arr = arr.concat(building.pointTypeCountVOMap[key].mediaPointList.filter(point => point.work_order_id !== null))
        }
      })
      return arr
    },
    initMediaTypeSpecPriceArr() {
      all().then(res => {
        this.media_type_spec_price_arr = res.data
      })
    },
    getSpecPriceName(id) {
      if (id !== null && id !== undefined) {
        let find = this.media_type_spec_price_arr.find(item => item.id === id)
        if (find) {
          return '(' + find.media_type_spec_name + ')'
        } else {
          return undefined
        }
      }
      return undefined
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .choosed-data {
  background-color: #e9f9ff !important;
}

/deep/ .dataTable .el-table__footer td {
  background-color: #e9f9ff !important;
}

/deep/ .look_conflict_button {
  position: fixed;
  top: calc(50vh - 45px);
  right: 10px;
}

/deep/ .look_conflict_button span {
  writing-mode: tb-rl;
}

/deep/ .el-drawer__close-btn {
  text-align: right;
}

.item {
  width: 70px;
  height: 70px;
  text-align: center;
  display: table;
  padding: 5px;
  margin: 10px 5px;
  border: 1px dashed #ddd;
  border-radius: 10px;
}

.checked-box {
  background-color: rgba(215, 240, 219, .8);
  border-style: solid;
}

.to_right {
  width: 0;
  height: 0;
  border-bottom: 15px solid transparent;
  border-left: 16px solid #409EFF;
  border-top: 15px solid transparent;
}
</style>
